﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace DAL
{
    public class UserService
    {
        String strConn = @"Data Source=TYL\MSSQLSERVER2008;Initial Catalog=EasyBuy;uid=sa;pwd=cddx;";


        String SELECT_USER_BY_Name = "select UID,UName,UPassWord,Ustatus from users where UName=@UName and  UPassWord=@UPassWord";
        String INSERT_USER = "insert into users(UName,UPassWord,Ustatus) values(@UName,@UPassWord,@Ustatus) ";

        /// <summary>
        /// DAL层登录方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public MODEL.User dalLogin(String name, String password)
        {
            MODEL.User user = null;
            using (SqlConnection conn = new SqlConnection(strConn))
            {
                using (SqlCommand cmd = new SqlCommand(SELECT_USER_BY_Name, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@UName", name);
                    cmd.Parameters.AddWithValue("@UPassWord", password);
                    using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                    {
                        if (dr.Read())
                        {
                            user = new MODEL.User();
                            user.UID = dr.GetInt32(0);
                            user.UName = dr.GetString(1);
                            user.UPwd = dr.GetString(2);
                            user.UStatus = dr.GetString(3);
                        }
                    }
                }
            }
            return user;
        }

        /// <summary>
        /// DAL层注册方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool dalRegist(String name, String password)
        {
            using (SqlConnection conn = new SqlConnection(strConn))
            {
                using (SqlCommand cmd = new SqlCommand(INSERT_USER, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@UName", name);
                    cmd.Parameters.AddWithValue("@UPassWord", password);
                    cmd.Parameters.AddWithValue("@Ustatus", "1");
                    int num = cmd.ExecuteNonQuery();
                    return num == 1 ? true : false;
                }
            }
        }

    }
}
